// ignore_for_file: must_be_immutable

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    home: MyText2(),
  ));
}

// stateLess组件在改变变量时不会重新build，所以不会相应
class MyText1 extends StatelessWidget {
  MyText1({super.key});
  int _size = 0;
  void Function()? onPressed() {
    _size += 1;
    print(_size);
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('$_size'),
        ElevatedButton.icon(
          onPressed: onPressed,
          label: const Text('加'),
          icon: const Icon(Icons.add),
        )
      ],
    );
  }
}

// stateFull  组件在改变状态时会重新build,所以是响应的
class MyText extends StatefulWidget {
  const MyText({super.key});

  @override
  State<MyText> createState() => MyTextState();
}

class MyTextState extends State<MyText> {
  int _num = 0;
  void Function()? onPressed() {
    // 执行setState时会重新build
    setState(() {
      _num++;
    });
    return null;
  }

  void Function()? handlePress() {
    setState(() {
      _num++;
    });
    return null;
  }

  @override
  Widget build(BuildContext context) {
    print(_num);
    return Scaffold(
      appBar: AppBar(title: const Text('这是列表页面')),
      body: Container(
        child: Column(
          children: [
            Text('$_num'),
            ElevatedButton(onPressed: onPressed, child: const Text('加'))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: handlePress,
        child: const Icon(Icons.add),
      ),
    );
  }
}

class MyText2 extends StatefulWidget {
  const MyText2({super.key});

  @override
  State<MyText2> createState() => _MyText2State();
}

class _MyText2State extends State<MyText2> {
  int num = 10;
  void Function()? onPressed() {
    setState(() {
      num++;
    });
    return null;
  }

  List<Widget> renderList() {
    List<Widget> list = [];
    for (var k = 0; k < num; k++) {
      list.add(ListTile(title: Text('这是一条列表项$k')));
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('这是标题')),
        body: ListView(
          children: [
            ...renderList(),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: onPressed,
          child: const Icon(Icons.add),
        ));
  }
}
